package com.itcs.box.server.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import io.netty.channel.ChannelHandlerContext;

/**
 * 
 * @author LiuPeng
 * 
 */
public class NettyChannelMap {

	private static Log logger = LogFactory.getLog(NettyChannelMap.class);

	private static Map<String, ChannelHandlerContext> map = new ConcurrentHashMap<String, ChannelHandlerContext>();

	private static Map<String, String> channelIdMap = new ConcurrentHashMap<String, String>();

	public static void add(String clientId, String channelId, ChannelHandlerContext socketChannel) {
		logger.info("client:[" + clientId + "],登录成功");
		map.put(clientId, socketChannel);
		channelIdMap.put(clientId, channelId);
	}

	public static ChannelHandlerContext get(String clientId) {
		return map.get(clientId);
	}

	public static void remove(String clientId) {
		map.remove(clientId);
		channelIdMap.remove(clientId);
		logger.info("client:" + clientId + ",下线");
	}

	/**
	 * 根据通道获取设备ID
	 * 
	 * @param socketChannel
	 * @return
	 */
	public static String getKeyByValue(ChannelHandlerContext socketChannel) {
		for (Map.Entry<String, ChannelHandlerContext> entry : map.entrySet()) {
			if (entry.getValue() == socketChannel) {
				return entry.getKey();
			}
		}
		return null;
	}

	public static Map<String, ChannelHandlerContext> getMap() {
		return map;
	}

	public static void setMap(Map<String, ChannelHandlerContext> map) {
		NettyChannelMap.map = map;
	}

	/**
	 * 判断是否存在
	 * 
	 * @param clientId
	 * @return
	 */
	public static boolean isNotExists(String clientId) {
		return !map.containsKey(clientId);
	}

	/** 
	 * 通过deviceId查找channelId
	 * @param deviceId
	 * @return 
	 */
	public static String getChannelId(String deviceId) {
		return channelIdMap.get(deviceId);
	}
}
